#include "Cards.h"

Cards::Cards() {}

Cards::Cards(const Card &card)
{
    add(card);
}

void Cards::add(const Card &card)
{
    m_cards.insert(card);
}

void Cards::add(const Cards &cards)
{
    m_cards.unite(cards.m_cards);
}

void Cards::add(const QVector<Cards> &cards)
{
    for(int i=0; i<cards.count(); ++i)
    {
        add(cards.at(i));
    }
}

void Cards::remove(Card &card)
{
    m_cards.remove(card);
}

void Cards::remove(const Cards &cards)
{
    m_cards.subtract(cards.m_cards);
}

void Cards::remove(const QVector<Cards> &cards)
{
    for(int i = 0;i<cards.size();i++){
        remove(cards[i]);
    }
}

Cards &Cards::operator <<(const Card &card)
{
    add(card);
    return *this;
}

Cards &Cards::operator <<(const Cards &cards)
{
    add(cards);
    return *this;
}

int Cards::cardCount()
{
    return m_cards.size();
}

bool Cards::isEmpty()
{
    return m_cards.isEmpty();
}

void Cards::clear()
{
    m_cards.clear();
}

Card::CardPoint Cards::maxPoint()
{
    Card::CardPoint max = Card::Card_Begin;
    if(!m_cards.isEmpty()){//不为空才判断
        for(const auto& it : m_cards){
            if(it.point() > max){
                max = it.point();
            }
        }
    }
    return max;//返回最大值或为空返回0
}

Card::CardPoint Cards::minPoint()
{
    Card::CardPoint min = Card::Card_End;
    if(!m_cards.isEmpty()){//不为空才判断
        for(const auto& it : m_cards){
            if(it.point() < min){
                min = it.point();
            }
        }
    }
    return min;//返回最小值或为空返回end(最大)
}

int Cards::pointCount(Card::CardPoint point)
{
    int count = 0;
    for(const auto& it : m_cards){
        if(it.point() == point){
            count++;
        }
    }
    return count;//返回个数
}

bool Cards::contains(const Card &card)
{
    return m_cards.contains(card);
}

bool Cards::contains(const Cards &cards)
{
    return m_cards.contains(cards.m_cards);
}

Card Cards::takeRandCard()
{
    //生成一个随机数
    int num = QRandomGenerator::global()->bounded(m_cards.size());
    QSet<Card>::const_iterator it = m_cards.constBegin();//常量迭代器
    for(int i=0; i<num; ++i,++it);//QSet不能通过下标直接访问元素，所以必须使用迭代器逐个访问元素
    Card card = *it;//得到选取位置的牌
    m_cards.erase(it);//删除选取的牌
    return card;
}

CardList Cards::toCardList(SortType type)
{
    //qsort被废弃，官方明确说要用C++本身的sort函数
    CardList list;
    for(auto& it : m_cards){
        list << it;
    }
    if(type == Asc){
        std::sort(list.begin(),list.end(),lessSort);//升序

    }else if(type == Desc){
        std::sort(list.begin(),list.end(),greaterSort);//降序
    }
    return list;
}


